<template>
  <div class="hide-page-wrapper page-wrapper noneditable irremovable" :data-edit-content-type="editContentType"
    :data-file-property-name="filePropertyName">
    <DocTitle v-if="isPreview" />
    <component v-for="pageName of headPages" :is="pageName" :data-page-id="getPageId(pageName)"
      :data-page-type="pageName" :propsData="getPropsData(pageName)" :key="getPageId(pageName)" />
    <Content v-for="item of contentPages" :key="item.pageId" :data-page-id="item.pageId"
      :data-content-page-type="item.dataType" :data-page-type="'content'" :propsData="item" />
    <Annex v-for="item of annexPages" :key="item.pageId" :data-page-id="item.pageId" :data-page-type="'annex'"
      :propsData="item" :data-annex-type="item.pageType" />
    <component v-for="pageName of tailPages" :is="pageName"
      :contenteditable="pageName !== 'index' && pageName !== 'indexEn'" :data-page-id="getPageId(pageName)"
      :data-page-type="pageName" :propsData="getPropsData(pageName)" :key="getPageId(pageName)" />
  </div>
</template>

<script>
  import { mapGetters } from 'vuex'

  import Cover from './pages/Cover.vue'
  import Annex from './pages/Annex.vue'
  import Content from './pages/Content.vue'
  import Contents from './pages/Contents.vue'
  import Foreword from './pages/Foreword.vue'
  import Index from './pages/Index.vue'
  import IndexEn from './pages/IndexEn.vue'
  import Introduction from './pages/Introduction.vue'
  import Reference from './pages/Reference.vue'
  import Revision from './pages/Revision.vue'
  import Signature from './pages/Signature.vue'
  import DocTitle from './blocks/DocTitle.vue'
  import { loadVaribles, getStatusByDocno, initLoadVariableContents, getEventInfo } from '@/api/computingConfig.js'
  import { getDocumentVariableList } from '@/api/variable.js'
  import { v4 as uuid } from "uuid";
  import store from '@/store'
  import { refreshTableNumbers } from '@/utils/plugins/table/noteSetting'
  import { refreshFigureNumbers } from '@/utils/plugins/image/figureSetting.js'
  export default {
    components: {
      DocTitle,
      Cover,
      Annex,
      Content,
      Contents,
      Foreword,
      Index,
      IndexEn,
      Introduction,
      Reference,
      Revision,
      Signature
    },
    created() {
      const isEmbedded = window._vueobj.$store.getters._iframe
      // 如果是内嵌的iframe，即引用内容功能，则使用自己的store
      this.$store = isEmbedded ? window._vueobj.$store : window.parent._vueobj.$store
    },
    data() {
      return {
        algos: [],
        variables: [],
        docStatus: null,
        loading: true
      }
    },
    computed: {
      contentPages() {
        return this.$store.getters.contentPages
      },
      _iframe() {
        return this.$store.getters._iframe
      },
      editContentType() {
        return this.$store.getters.editContentType
      },
      entry() {
        return this.$store.getters.entry
      },
      filePropertyName() {
        return this.$store.getters.filePropertyName
      },
      isPreview() {
        return this.entry === 'htmlpreview'
      },
      pageTypes() {
        return this.editorPageList.map((i) => i.pageType)
      },
      headPages() {
        const need = ['foreword', 'introduction']
        // 该项目不显示 'cover', 'signature', 'revision'
        const arr = this.isPreview ? (this._iframe ? [] : need) : ['contents', ...need]
        return arr.filter((i) => this.pageTypes.includes(i))
      },
      annexPages() {
        if (this._iframe) return []
        return this.$store.getters.annexPages
      },
      tailPages() {
        if (this._iframe) return []
        const arr = ['reference', 'index', 'indexEn']
        return arr.filter((i) => this.pageTypes.includes(i))
      },
      editorPageList() {
        return this.$store.state.xmleditor.editorPageList
      }
    },
    methods: {
      getPropsData(pageType) {
        return this.editorPageList.find((i) => i.pageType === pageType)
      },
      getPageId(pageType) {
        return this.editorPageList.find((i) => i.pageType === pageType)?.pageId
      },
      async nodeProcess(node, data, type, name) {
        node.forEach(async el => {
          if ((el.nodeName == 'CAPTION' || el.tagName == 'CAPTION') && type == 'variable_table_algo') {
            const caption = el.querySelector('p');
            if (!caption.innerText?.includes(data?.resultName)) {
              const arr = caption.innerText?.split('-');
              arr.splice(1, 0, data?.resultName);
              caption.innerText = `${arr[0]?.trim()}-${arr[1]?.trim()}-${arr[2]?.trim()}`;
            }
          }
          // 表头设置
          if (el.nodeName == 'THEAD' || el.tagName == 'THEAD') {
            let tr = '';
            let titles = data?.titles || [];
            if (type == 'variable_table_algo' || type == 'variable_table_algo_all') {
              titles.unshift('序号')
            }
            if (titles.length > 0) {
              titles.forEach(title => {
                let th = '';
                th = `<th colspan="1" rowspan="1" data-id="${uuid()}">
		                    <p data-type="paragraph" data-lang="zh">${title}​</p>
	                    </th>`
                tr += th;
              })
              tr = `<tr data-id="${uuid()}">${tr}</tr>`
            }
            el.innerHTML = tr
          }
          // 数据设置
          if (el.nodeName == 'TBODY' || el.tagName == 'TBODY') {
            let tbody = '';
            const datas = data?.data || [];
            let columns = data?.columns || [];
            if (type == 'variable_table_algo' || type == 'variable_table_algo_all') {
              columns.unshift('index');
            }
            let firstIndex = 1;
            if (datas.length > 0) {
              datas.forEach(async (dataItem) => {
                let tr = '';
                columns.forEach((tdData, index) => {
                  let td = '';
                  if (index == 0 && (type == 'variable_table_algo_all' || type == 'variable_table_algo')) {
                    td = `<td colspan="1" rowspan="1" data-id="${uuid()}">
		                    <p data-type="paragraph" data-lang="zh">${firstIndex}​</p>
	                    </td>`
                  } else {
                    td = `<td colspan="1" rowspan="1" data-id="${uuid()}">
		                    <p data-type="paragraph" data-lang="zh">${dataItem[tdData] || ''}​</p>
	                    </td>`
                  }
                  tr += td;
                })
                firstIndex += 1;
                tbody += `<tr data-id="${uuid()}">${tr}</tr>`
              })

            }
            el.innerHTML = tbody
          }

        })
        await refreshTableNumbers(tinymce.activeEditor);
        console.log(node)
      },
      async dataValidate1() {
        const _this = this;
        await getStatusByDocno({ containMainBody: false, docNo: this.$store.state.xmleditor.docInfo.docNo }).then(async (res) => {
          if (res) {
            await setTimeout(async function () {
              _this.$store.commit('xmleditor/SET_DOC_STATUS', res?.data?.status)
              if (res?.data?.status != 0 && res?.data?.status != 9) {
                const el = document.getElementById("processDiv");
                el.style.display = 'none';
                location.reload();
              } else {
                // 获取事件状态
                let status = 'done';
                if (res?.data?.loadEventId) {
                  await getEventInfo({ ids: res?.data?.loadEventId, withoutResult: true, withoutHistory: false }).then(res => {
                    if (res) {
                      const content = res[0]?.currentInfo;
                      status = res[0]?.status;
                      const contentEl = document.getElementById("processContent");
                      contentEl.innerText = content;
                    }
                  });
                }
                if (status == 'Fail') {
                  return;
                }
                _this.dataValidate();
              }
            }, 5000)
          }
        })
      },
      async dataValidate() {
        const _this = this;
        await getStatusByDocno({ containMainBody: false, docNo: this.$store.state.xmleditor.docInfo.docNo }).then(async (res) => {
          if (res) {
            await setTimeout(async function () {
              _this.$store.commit('xmleditor/SET_DOC_STATUS', res?.data?.status)
              if (res?.data?.status != 0 && res?.data?.status != 9) {
                const el = document.getElementById("processDiv");
                el.style.display = 'none';
                location.reload();
              } else {
                // 获取事件状态
                let status = 'done';
                if (res?.data?.loadEventId) {
                  await getEventInfo({ ids: res?.data?.loadEventId, withoutResult: true, withoutHistory: false }).then(res => {
                    if (res) {
                      const content = res[0]?.currentInfo;
                      status = res[0]?.status;
                      const contentEl = document.getElementById("processContent");
                      contentEl.innerText = content;
                    }
                  });
                }
                if (status == 'Fail') {
                  return;
                }
                _this.dataValidate();

              }
            }, 5000)
          }
        })
      },
      //数组去重
      uniqueObjects(arr, key, key1) {
        const seen = new Set();
        const seen1 = new Set();
        return arr.filter(item => {
          const itemKey = item[key];
          const itemKey1 = item[key1];
          if (seen.has(itemKey) && seen.has(itemKey1)) {
            return false;
          }
          seen.add(itemKey);
          seen.add(itemKey1);
          return true;
        })
      },
      // 插入表格
      async insertTable(data, nodes, algoName, content) {
        const currentNode = tinymce.activeEditor.selection.select(nodes);
        tinymce.activeEditor.selection.collapse(false);
        let thead = '';
        let tbody = '';
        data?.titles?.forEach(title => {
          let th = '';
          th = `<th colspan="1" rowspan="1" data-id="${uuid()}">
		                    <p data-type="paragraph" data-lang="zh">${title}​</p>
	                    </th>`
          thead += th;
        });
        thead = `<tr data-id="${uuid()}" > ${thead}</tr>`;
        data?.data?.forEach((dataItem, index) => {
          let tr = '';
          data?.columns?.forEach(tdData => {
            let td = '';
            td = `<td colspan="1" rowspan="1" data-id="${uuid()}">
		                    <p data-type="paragraph" data-lang="zh">${dataItem[tdData] || ''}​</p>
	                    </td>`
            tr += td;
          })
          tbody += `<tr data-id="${uuid()}">${tr}</tr>`
        })
        const tableUUid = uuid();
        const captionUUid = uuid();
        // tinymce.activeEditor.insertContent(`<p data-type="paragraph" data-block-id="${uuid()}" data-id="${uuid()}">&nbsp;&nbsp;&nbsp;&nbsp;</p>`)
        tinymce.activeEditor.insertContent(`<p data-type="paragraph" data-block-id="${uuid()}" data-id="${captionUUid}">XX结构XX强度裕度汇总如表xx所示。从表中可知最小裕度出现在XX部位，
          ${content}，满足静强度要求。</p>`)
        tinymce.activeEditor.insertContent(
          `<table border="1" class="data-content-table" data-type="table"  data-block-id="${uuid()}" data-id="${tableUUid}" style="border-collapse: collapse; width: 98.0521%;" data-mce-selected="1">
              <caption data-id="${uuid()}" class="table_caption zh">
                  <p class="caption zh" >${algoName}-${data?.resultName}-裕度汇总表</p>
              </caption>
          <thead>
              ${thead}
          </thead>
              <tbody>
                  ${tbody}
              </tbody>
          </table>`
        );
        store.commit("xmleditor/UPDATE_DOC_STRUCTURE");
        await refreshTableNumbers(tinymce.activeEditor);
        // 获取tablenumber
        const doc = tinymce.activeEditor.getDoc();
        const tableContent = doc.querySelector(`[data-id='${tableUUid}']`);
        const captionContent = doc.querySelector(`[data-id='${captionUUid}']`);
        console.log('tableContent.dataset')
        console.log(tableContent.dataset)
        captionContent.innerText = captionContent.innerText.replace('表xx', `表${tableContent?.dataset?.number}`)

      }
    },
    mounted() {
      if (this.$route?.query?.algos) {
        this.algos = this.$route?.query?.algos;
        //根据状态执行不同的接口
        getStatusByDocno({ containMainBody: false, docNo: this.$route?.query?.docNo }).then(res => {
          if (res) {
            this.docStatus = res?.data?.status;
            this.$store.commit('xmleditor/SET_DOC_STATUS', this.docStatus)
          }
        })
        // this.docStatus = this.$route?.query?.docStatus;

        if (this.algos) {
          this.$store.commit('xmleditor/SET_REPORT_ALGOS', this.algos.split(','))
        }
      }
      this.$nextTick(async () => {
        if (this.$store.getters.editContentType === 'document') {
          await getDocumentVariableList({
            pageNum: 1,
            pageSize: 100,
          }).then(res => {
            this.variables = res?.data?.list || [];
            //缓存所有变量内容
            store.commit('xmleditor/SET_ALL_VARIABLES', res?.data?.list)
          })
          console.log("页面加载完成")
          const variables = ['variable_string', 'variable_hide_string', 'variable_table', 'variable_chapt', 'table', 'chapter', 'variable_string_summary',
            'variable_string_relationFiles', 'variable_string_algos_name', 'variable_hide_string_symbol', 'variable_string_stuctrue']
          const doc = tinymce.activeEditor.getDoc();
          const editor = tinymce.activeEditor;
          let variablePushArr = new Set();
          await variables.forEach(item => {
            const pageNodes = doc?.querySelectorAll(`[data-type=${item}]`);
            if (pageNodes && pageNodes.length > 0) {
              pageNodes.forEach(el => {
                if (el.getAttribute('data-variable-id')) {
                  let canPush = false;
                  this.variables.forEach(item => {
                    if (item.id == Number.parseInt(el.getAttribute('data-variable-id')) && item.variableConfig?.variableViewType != 'variable_table_algo') {
                      canPush = true;
                    }
                  })
                  if (canPush) {
                    variablePushArr.add(Number.parseInt(el.getAttribute('data-variable-id')))
                  }
                }
              })
            }
          })
          // 查询变量信息
          let variableList = [];
          if (variablePushArr.size > 0) {
            let currentStatus = null;
            await getStatusByDocno({ containMainBody: false, docNo: this.$store.state.xmleditor.docInfo.docNo }).then(res => {
              if (res) {
                currentStatus = res?.data?.status;
              }
            })
            console.log(currentStatus)
            if (currentStatus == 0 || currentStatus == 9) {
              let div = document.createElement('div');
              div.style.height = '100%'
              div.style.position = 'absolute'
              div.style.width = '100%'
              div.style.background = '#b5b5b5'
              div.style.top = '0'
              div.style.left = '0'
              div.style.opacity = 0.9;
              div.style.display = 'flex';
              div.style.alignItems = 'center';
              div.style.justifyContent = 'center';
              div.setAttribute("id", "processDiv")
              document.body.appendChild(div)
              let div1 = document.createElement('div');
              div1.innerText = '报告生成中，请耐心等待。。。。';
              div1.style.color = 'green';
              div1.setAttribute("id", "processContent")
              div.appendChild(div1);
              initLoadVariableContents({ docNo: this.$store.state.xmleditor.docInfo.docNo, ids: [...variablePushArr] });
              //查询进度
              await this.dataValidate();
            } else {//直接查询变量内容
              await loadVaribles({ docNo: this.$store.state.xmleditor.docInfo.docNo, ids: [...variablePushArr] }).then(res => {
                variableList = [...res?.data]
                //缓存所有变量内容
                store.commit('xmleditor/SET_ALL_VARIABLE_CONTENT', variableList)
              })
            }
          } else {
            return;
          }

          // 替换字符串变量
          const constantList = variableList.filter(item => {
            return item.variableConfig?.variableViewType.includes('variable_string') || item.variableConfig?.variableViewType.includes('variable_hide_string');
          })
          let docRefComposite = [];
          let docRefCompositeContent = null;
          //查询第六章引用文件变量
          await getDocumentVariableList({ variableCode: "dimDefSection" }).then(res => {
            docRefComposite = res?.data?.list;
          })
          await loadVaribles({ docNo: this.$store.state.xmleditor.docInfo.docNo, ids: [docRefComposite[0]?.id] }).then(res => {
            docRefCompositeContent = [...res?.data]
          })
          console.log("执行所有变量查询")
          console.log(variableList)
          console.log(constantList)
          //主要结构变量内容
          let mainStructor = null;
          // 算例名称集合
          let algoNamesConllection = [];
          // 引用文件集合
          let refFilesList = null;
          let refFilesNode = null;
          constantList.forEach(async (item) => {
            if (item?.variableCode == 'mainStructure') {
              mainStructor = item.variableContent;
            }

            if (item.variableContent && item.variableContent != []) {
              // 算例全部名称需要换行展示
              if (item?.variableConfig?.variableViewType == 'variable_string_algos_name') {
                let algosNamesDom = '';
                await item?.variableContent?.forEach((el, index) => {                  
                  let algoSpan = "";
                  if(index == item?.variableContent.length-1){
                    algoSpan = `<span style="padding-left:${index == 0 ? 0 : 0.8}cm;">${index + 1})、${el}</span>`;
                  }else{
                    algoSpan = `<span style="padding-left:${index == 0 ? 0 : 0.8}cm;">${index + 1})、${el}</span><br />`;
                  }
                  algosNamesDom += algoSpan;
                  algoNamesConllection.push(el);
                })
                const algosNodes = doc.querySelectorAll(`[data-variable-id="${item.id}"]`);
                algosNodes[0].innerHTML = algosNamesDom;

              }// 依据性文件渲染
              else if (item?.variableConfig?.variableViewType == 'variable_string_relationFiles') {
                let algosNamesDom = '';
                await item?.variableContent?.forEach((el, index) => {
                  let algoSpan = `<span style="padding-left:${index == 0 ? 0 : 0.9}cm;">${el.fileCode}&nbsp;&nbsp;&nbsp;&nbsp;${el.fileName}</span><br />`;
                  algosNamesDom += algoSpan;
                })
                const algosNodes = doc.querySelectorAll(`[data-variable-id="${item.id}"]`);
                algosNodes[0].innerHTML = algosNamesDom;
              }// 符号渲染
              else if (item?.variableConfig?.variableViewType == 'variable_hide_string_symbol') {
                let algosNamesDom = '';
                const url = process.env.VUE_APP_BASE_API + "/editor/file/download/"
                await item?.variableContent?.data?.forEach((el, index) => {
                  let algoSpan = '';
                  let symbleImageUrl = "";
                  let symbleDesImageUrl = "";
                  if (el.symbolType == 'IMAGE') {
                    symbleImageUrl = `${url}${el.symbolKey}`;
                  }
                  if (el.symbolType == 'FORMULA_DATA') {
                    const symbleObj = JSON.parse(el.symbolKey);
                    symbleImageUrl = `${symbleObj.url}`;
                  }
                  if (el.symbolDescribeType == 'IMAGE') {
                    symbleDesImageUrl = `${url}${el.symbolDescribe}`;
                  }
                  if (el.symbolDescribeType == 'FORMULA_DATA') {
                    const symbleDesObj = JSON.parse(el.symbolDescribe);
                    symbleDesImageUrl = `${symbleDesObj.url}`;
                  }
                  // 图片符号
                  if (el.symbolType == 'TEXT' && el.symbolDescribeType == 'TEXT') {
                    if (item?.variableContent?.data.length - 1 == index) {
                      algoSpan = `<span style="padding-left:${index == 0 ? 0 : 0.8}cm;text-indent: initial;display: inline-flex;width:100%;height: 40px;align-items: center;"><span style="height: 40px;display: inline-flex;align-items: center;line-height: 40px;text-indent: initial;">${el.symbolKey}——${el.symbolName}</span>${el?.symbolDescribe ? '，' + el.symbolDescribe + ' 。' : ' 。'}</span><br />`;
                    } else {
                      algoSpan = `<span style="padding-left:${index == 0 ? 0 : 0.8}cm;text-indent: initial;display: inline-flex;width:100%;height: 40px;align-items: center;"><span style="height: 40px;display: inline-flex;align-items: center;line-height: 40px;text-indent: initial;">${el.symbolKey}——${el.symbolName}</span>${el?.symbolDescribe ? '，' + el.symbolDescribe + ' ;' : ' ;'}</span><br />`;
                    }
                  }
                  if (el.symbolType == 'TEXT' && (el.symbolDescribeType == 'IMAGE' || el.symbolDescribeType == 'FORMULA_DATA')) {
                    if (item?.variableContent?.data.length - 1 == index) {
                      algoSpan = `<span style="padding-left:${index == 0 ? 0 : 0.8}cm;text-indent: initial;display: inline-flex;width:100%;height: 40px;align-items: center;"><span style="height: 40px;display: inline-flex;align-items: center;line-height: 40px;text-indent: initial;">${el.symbolKey}——${el.symbolName}</span>${el?.symbolDescribe ? `， <img src="${symbleDesImageUrl}" width="8%" height="20" alt="" data-mce-src="${symbleDesImageUrl}"> 。` : ' 。'}</span><br />`;
                    } else {
                      algoSpan = `<span style="padding-left:${index == 0 ? 0 : 0.8}cm;text-indent: initial;display: inline-flex;width:100%;height: 40px;align-items: center;"><span style="height: 40px;display: inline-flex;align-items: center;line-height: 40px;text-indent: initial;">${el.symbolKey}——${el.symbolName}</span>${el?.symbolDescribe ? `， <img src="${symbleDesImageUrl}" width="8%" height="20" alt="" data-mce-src="${symbleDesImageUrl}">;` : ' ;'}</span><br />`;
                    }
                  }
                  if ((el.symbolType == 'IMAGE' || el.symbolType == 'FORMULA_DATA') && (el.symbolDescribeType == 'IMAGE' || el.symbolDescribeType == 'FORMULA_DATA')) {
                    if (item?.variableContent?.data.length - 1 == index) {
                      algoSpan = `<span style="padding-left:${index == 0 ? 0 : 0.8}cm;text-indent: initial;display: inline-flex;width:100%;height: 40px;align-items: center;">
                        <img src="${symbleImageUrl}" width="8%" height="20" alt="" data-mce-src="${symbleImageUrl}">
                        ——${el.symbolName}${el?.symbolDescribe ? `， <img src="${symbleImageUrl}" width="8%" height="20" alt="" data-mce-src="${symbleImageUrl}"> 。` : ' 。'}</span><br />`;
                    } else {
                      algoSpan = `<span style="padding-left:${index == 0 ? 0 : 0.8}cm;text-indent: initial;display: inline-flex;width:100%;height: 40px;align-items: center;">
                        <img src="${symbleImageUrl}" width="8%" height="20" alt="" data-mce-src="${symbleImageUrl}">
                        ——${el.symbolName}${el?.symbolDescribe ? `， <img src="${symbleDesImageUrl}" width="8%" height="20" alt="" data-mce-src="${symbleDesImageUrl}">;` : ' ;'}</span><br />`;
                    }
                  }
                  if ((el.symbolType == 'IMAGE' || el.symbolType == 'FORMULA_DATA') && el.symbolDescribeType == 'TEXT') {
                    if (item?.variableContent?.data.length - 1 == index) {
                      algoSpan = `<span style="padding-left:${index == 0 ? 0 : 0.8}cm;text-indent: initial;display: inline-flex;width:100%;height: 40px;align-items: center;">
                        <img src="${symbleImageUrl}" width="8%" height="20" alt="" data-mce-src="${symbleImageUrl}">
                        <span style="height: 40px;display: inline-flex;align-items: center;line-height: 40px;text-indent: initial;">——${el.symbolName}</span>${el?.symbolDescribe ? '，' + el.symbolDescribe + ' 。' : ' 。'}</span><br />`;
                    } else {
                      algoSpan = `<span style="padding-left:${index == 0 ? 0 : 0.8}cm;text-indent: initial;display: inline-flex;width:100%;height: 40px;align-items: center;">
                        <img src="${symbleImageUrl}" width="8%" height="20" alt="" data-mce-src="${symbleImageUrl}">
                        <span style="height: 40px;display: inline-flex;align-items: center;line-height: 40px;text-indent: initial;">——${el.symbolName}</span>${el?.symbolDescribe ? '，' + el.symbolDescribe + ' ;' : ' ;'}</span><br />`;
                    }
                  }
                  algosNamesDom += algoSpan;
                })
                const algosNodes = doc.querySelectorAll(`[data-variable-id="${item.id}"]`);
                // algosNodes[0].outerHTML = algosNamesDom;
                algosNodes[0].innerHTML = algosNamesDom;
              }
              else if (item?.variableConfig?.variableViewType == 'variable_string_summary') {
                let algosNamesDom = '';
                const tempData = this.uniqueObjects(item?.variableContent, "code", "name") || [];
                await tempData.forEach((el, index) => {
                  let algoSpan = `<span style="padding-left:${0.8}cm;">${el.code}&nbsp;&nbsp;&nbsp;&nbsp;${el.name}</span><br />`;
                  algosNamesDom += algoSpan;
                })
                const algosNodes = doc.querySelectorAll(`span[data-variable-id="${item.id}"]`);
                algosNodes[0].innerHTML += algosNamesDom;
                refFilesNode = algosNodes[0];
                console.log("variable_string_summary")
                console.log(refFilesNode)
              } else if (item?.variableConfig?.variableViewType == 'variable_string_stuctrue') {
                const groupId = uuid()
                const structureData = JSON.parse(item?.variableContent?.jsonContent)?.filter((i) => i?.dataType !== 'blank_page');
                store.commit('xmleditor/SET_BLOCK_LIST', structureData)
                setTimeout(() => {
                  const type = 'collect'
                  const dom = document.querySelector(`#blockList${type === 'collect' ? ' .group-block' : ''}`)
                  dom.querySelectorAll('[data-id]').forEach((node) => {
                    tinymce.activeEditor.dom.setAttribs(node, {
                      'data-id': uuid(),
                      'data-group-id': groupId,
                      'data-block-type': type
                    })
                  })
                  const domNode = doc.querySelectorAll(`[data-variable-id="${item.id}"]`);
                  tinymce.activeEditor.selection.select(domNode[0])
                  tinymce.activeEditor.insertContent(dom.innerHTML)
                  store.commit('xmleditor/UPDATE_DOC_STRUCTURE')
                  // 光标回滚到第一行
                  setTimeout(() => {
                    const domNodeFirst = doc.querySelectorAll(`[data-index="1"]`);
                    tinymce.activeEditor.selection.select(domNodeFirst[0]);
                  }, 1000)
                })
              }
              else {
                const nodes = doc.querySelectorAll(`[data-variable-id="${item.id}"]`)
                for (let i = 0; i < nodes.length; i++) {
                  nodes[i].innerText = item.variableContent;
                }
              }

            }
          })
          //设置引用文件列表
          if (docRefCompositeContent?.length > 0) {
            refFilesList = docRefCompositeContent[0]?.variableContent?.refDocs;
            const files = await constantList.filter(el => {
              return el?.variableCode == 'docRefComposite'
            })
            let algosNamesDom = '';
            if (files.length > 0) {
              const tempData = this.uniqueObjects(files[0]?.variableContent, "code", "name") || [];
              tempData.forEach((el, index) => {
                let algoSpan = `<span style="padding-left:${index==0?0:0.8}cm;">${el.code}&nbsp;&nbsp;&nbsp;&nbsp;${el.name}</span><br />`;
                algosNamesDom += algoSpan;
              })
            }

            if (refFilesList?.length > 0) {
              refFilesList.forEach((el, index) => {
                let algoSpan = `<span style="padding-left:${ 0.8}cm;">${el.code}&nbsp;&nbsp;&nbsp;&nbsp;${el.name}</span><br />`;
                algosNamesDom += algoSpan;
              })
            }
            const algosNodes = doc.querySelectorAll(`span[data-variable-id="${files[0]?.id}"]`);
            algosNodes[0].innerHTML = algosNamesDom;
            // }
          }
          // 替换裕度汇总表
          const charptList = variableList.filter(item => {
            return item.variableConfig?.variableViewType.includes('variable_chapt');
          })
          const algosIds = this.variables.filter(el => {
            return el.variableConfig?.variableViewType == 'variable_table_algo'
          })
          const algosNodes = doc.querySelectorAll(`[data-variable-id="${algosIds[0]?.id}"]`)
          charptList[0]?.variableContent?.forEach(async (item, index) => {
            const data = await item?.resultTemplateVars?.filter(el => {
              return el.varId == algosIds[0]?.id
            });
            const contentList = await item?.resultTemplateVars?.filter(el => {
              return el.varCode == 'algoMsMinSentenceList'
            });
            const contentListVal = contentList[0].varValue;
            const tableChildren = doc.querySelector(`[data-id='${algosNodes[index]?.dataset?.id}']`).childNodes;
            //循环算例结果表
            const algoResultTable = data[0]?.varValue || [];
            await algoResultTable.forEach(async (el, index1) => {
              if (index1 == 0) {
                this.nodeProcess(tableChildren, el, 'variable_table_algo', algosNodes[index]);
              } else {
                const algoName = algoNamesConllection[index];
                await this.insertTable(el, algosNodes[index], algoName, contentListVal[index1]);
              }
            })
            // 替换字符串变量
            await item?.resultTemplateVars.forEach(algoString => {
              if (algoString?.varConfig?.variableViewType == 'variable_string_algo') {
                const algoStringNode = doc.querySelectorAll(`[data-variable-id="${algoString?.varId}"]`);
                if (algoString.varValue) {
                  algoStringNode[index].innerText = algoString.varValue[0];
                }
              }
              if (algoString?.varConfig?.variableViewType == 'variable_hide_string') {
                const algoStringNode = doc.querySelectorAll(`[data-variable-id="${algoString?.varId}"]`);
                const tableDom = doc.querySelectorAll(`[data-variable-id="${data[0]?.varId}"]`);
                if (algoStringNode) {
                  algoStringNode[index].innerText = tableDom[index]?.getAttribute('data-number');
                }
              }
            })
          })

          // 替换算例裕度汇总表的表名称
          const algoTableNodeLength = algosNodes.length;
          for (let k = 0; k < algoTableNodeLength; k++) {
            const algoTableNodeCaption = algosNodes[k].querySelector('caption');
            let captionP = algoTableNodeCaption.querySelector('p');
            if (algoNamesConllection[k] && !captionP.innerText.includes(algoNamesConllection[k])) {
              captionP.innerText = `${algoNamesConllection[k].trim()}-${captionP.innerText.trim()}`;
            }
          }
          //替换表格
          const tableList = variableList.filter(item => {
            return item.variableConfig?.variableViewType.includes('table');
          })
          let tableVariables = [];
          tableList.forEach(async (item) => {
            const nodes = doc.querySelectorAll(`[data-variable-id="${item.id}"]`)
            for (let i = 0; i < nodes.length; i++) {
              // 缓存table变量
              tableVariables.push({ dataId: nodes[i].getAttribute('data-id'), tableType: item.variableConfig?.variableViewType })
              if (item.variableConfig?.variableViewType == 'variable_table_auto' || item.variableConfig?.variableViewType == 'variable_table_algo_all') {
                const tableChildren = nodes[i].childNodes;
                if (item.variableContent) {
                  this.nodeProcess(tableChildren, item.variableContent, item.variableConfig?.variableViewType)
                }
              }
              //条款展示调整居中
              if (item.variableConfig?.variableViewType == 'variable_table_provision') {
                const provisionTableNode = doc.querySelector(`[data-variable-id="${item.id}"]`);
                const provisionTableNodeTbody = provisionTableNode.querySelector('tbody');
                const nodeTrs = provisionTableNodeTbody.querySelectorAll('tr');
                for (let nodeIndex = 0; nodeIndex < nodeTrs.length; nodeIndex++) {
                  const tds = nodeTrs[nodeIndex].querySelectorAll('td');
                  const pNode = tds[2]?.querySelector("p");
                  if (pNode) {
                    pNode.style = "text-align:left;";
                  }
                }
              }
              //总体裕度汇总表修改表头名称
              if (item.variableConfig?.variableViewType == 'variable_table_algo_all') {
                const algoALLTableNode = doc.querySelector(`[data-variable-id="${item.id}"]`);
                const algoALLTableNodeCaption = algoALLTableNode.querySelector('caption');
                let captionP = algoALLTableNodeCaption.querySelector('p');
                if (mainStructor) {
                  captionP.innerText = `${mainStructor}${captionP.innerText}`;
                }

              }
            }
            this.$store.commit('xmleditor/SET_TABLE_VARIABLES', tableVariables)
          })
          refreshTableNumbers(tinymce.activeEditor);
          // 替换表注
          const tableIndexMap = [
            { tableName: 'provision', tableIndexName: 'provision.tableNumber' },
            { tableName: 'material', tableIndexName: 'material.tableNumber' },
            { tableName: 'fastener', tableIndexName: 'fastener.tableNumber' },
            { tableName: 'msSummary', tableIndexName: 'msSummary.tableNumber' },
            { tableName: 'loadCaseStatistics', tableIndexName: 'loadCaseStatistics.tableNumber' },
            { tableName: 'algoResultTable', tableIndexName: 'algoResultTable.tableNumber' },
          ]
          tableIndexMap.forEach(async (item) => {
            const tableVariableInfo = variableList.filter(el => {
              return el.variableCode == item.tableName;
            })
            const tableIndexVariableInfo = variableList.filter(el => {
              return el.variableCode == item.tableIndexName;
            })
            //查找table的dom
            const tableDom = doc.querySelector(`[data-variable-id="${tableVariableInfo[0]?.id}"]`)
            const tableIndexDom = doc.querySelector(`[data-variable-id="${tableIndexVariableInfo[0]?.id}"]`)
            if (tableIndexDom) {
              if (item.tableIndexName == 'material.tableNumber') {
                let meterialIndexStr = [];
                const allTableNode = doc.querySelectorAll(`[data-type="table"]`);
                const meterialTableNode = [];
                allTableNode.forEach(item => {
                  if (item?.dataset?.variableId?.includes('0000')) {
                    meterialTableNode.push(item);
                  }
                })
                meterialTableNode.forEach(tableNode => {
                  meterialIndexStr.push(tableNode?.getAttribute('data-number'));
                })
                if (meterialIndexStr.length > 0) {
                  tableIndexDom.innerText = `${tableDom?.getAttribute('data-number')},${meterialIndexStr.toString()}`;
                } else {
                  tableIndexDom.innerText = tableDom?.getAttribute('data-number');
                }
              } else {
                tableIndexDom.innerText = tableDom?.getAttribute('data-number');
              }
            }
            // 算例结果表标注替换
            if (item.tableName == 'algoResultTable') {
              const algoResultTableIndexStr = this.variables.filter(el => {
                return el.variableCode == 'algoResultTable.tableNumber';
              })
              const algoResultTableName = this.variables.filter(el => {
                return el.variableCode == 'algoResultTable';
              })
              const algoTableDom = doc.querySelectorAll(`[data-variable-id="${algoResultTableIndexStr[0]?.id}"]`)
              const algoTableIndexDom = doc.querySelectorAll(`[data-variable-id="${algoResultTableName[0]?.id}"]`)
              algoTableIndexDom.forEach((item, index) => {
                const algoTableNumber = item?.getAttribute('data-number');
                algoTableDom[index].innerText = algoTableNumber
              })
            }
          })

          // 刷新公式编号
          await editor.fire('updateFormulaNumber')
          const algosTemplateVars = this.$store.state.xmleditor.algoTemplateVars;
          let algoFormulaNumbers = [];
          algosTemplateVars.forEach(async el => {
            const formulaNodes = editor.getDoc()?.querySelector(`[data-id="${el.variableContent.dataId}"]`)
            const formulaNumber = formulaNodes.getAttribute("data-formula-number");
            //设置当前变量值
            const formulaUseNode = editor.getDoc()?.querySelectorAll(`[data-variable-id="${el.id}"]`) || [];
            if (formulaUseNode[0]) {
              formulaUseNode[0].innerText = `(${formulaNumber})`;
              formulaUseNode[0].outerText = `(${formulaNumber})`;
            }

          });
          // 刷新图片编号
          await refreshFigureNumbers(editor);
          const algosPicVars = this.$store.state.xmleditor.algoPicVars;
          let algosPicNumbers = [];
          algosPicVars.forEach(async el => {
            const picNodes = editor.getDoc()?.querySelector(`[data-id="${el.variableContent.dataId}"]`)
            const picNumber = picNodes.getAttribute("data-number");
            //设置当前变量值
            const picUseNode = editor.getDoc()?.querySelectorAll(`[data-variable-id="${el.id}"]`) || [];
            if (picUseNode[0]) {
              picUseNode[0].innerText = `(${picNumber})`;
              picUseNode[0].outerText = `(${picNumber})`;
            }

          });
          // 刷新算例表格编号
          const algosTablesVars = this.$store.state.xmleditor.algosTablesVars;
          algosTablesVars.forEach(async el => {
            const tableNodes = editor.getDoc()?.querySelector(`[data-id="${el.variableContent.dataId}"]`)
            const algoTableNumber = tableNodes.getAttribute("data-number");
            //设置当前变量值
            const algoTableUseNode = editor.getDoc()?.querySelectorAll(`[data-variable-id="${el.id}"]`) || [];
            if (algoTableUseNode[0]) {
              algoTableUseNode[0].innerText = `(${algoTableNumber})`;
              algoTableUseNode[0].outerText = `(${algoTableNumber})`;
            }

          });
        }
      })
    }

  }
</script>

<style>
  .hide-page-wrapper {
    display: none;
  }
</style>